package com.baijiayun.live.ui.setting;

import android.view.View;
import com.baijia.bjydialog.MaterialDialog;
import com.baijiayun.live.ui.LiveSDKWithUI;
import com.baijiayun.live.ui.R;
import com.baijiayun.live.ui.activity.LiveRoomBaseActivity;
import com.baijiayun.live.ui.activity.LiveRoomRouterListener;
import com.baijiayun.live.ui.menu.rightmenu.RightMenuContract;
import com.baijiayun.livecore.context.LPConstants;
import com.baijiayun.livecore.context.LPError;
import com.baijiayun.livecore.models.LPBleDevice;
import com.baijiayun.liveuibase.utils.RxUtils;
import com.baijiayun.liveuibase.utils.ThemeDataUtil;
import com.baijiayun.liveuibase.widgets.SettingSwitch;
import com.baijiayun.liveuibase.widgets.SwitchCompat.MultiSwitchCompat;
import com.baijiayun.liveuibase.widgets.dialog.ThemeMaterialDialogBuilder;
import com.baijiayun.liveuibase.widgets.setting.BaseSettingFragment;
import com.baijiayun.liveuibase.widgets.setting.BaseSettingPresenter;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wubanglin
 */

public class SettingDialogFragment extends BaseSettingFragment {
    private LiveRoomRouterListener liveRoomRouterListener;
    private static boolean shouldInitRemark = true;
    private static boolean mRemarksEnable = false;
    private Disposable subscriptionOfForbidAllChat, subscriptionOfMic, subscriptionOfCamera, subscriptionOfForbidRaiseHand,
            subscriptionOfUpLinkType, subscriptionOfDownLinkType, subscriptionOfForbidAllAudio, subscriptionOfChangePPT;
    private Disposable disposableOfMirrorModeSwitch;

    public static SettingDialogFragment newInstance() {
        SettingDialogFragment fragment = new SettingDialogFragment();
        return fragment;
    }

    @Override
    protected void initChildData() {
        liveRoomRouterListener = ((LiveRoomBaseActivity) getActivity()).getRouterListener();
        presenter.subscribe(liveRoomRouterListener.getLiveRoom());
    }

    @Override
    protected BaseSettingPresenter initPresenter() {
        return new BaseSettingPresenter(this) {
            @Override
            public void detachLocalVideo() {
                liveRoomRouterListener.detachLocalVideo();
            }

            @Override
            public void attachLocalVideo() {
                liveRoomRouterListener.attachLocalVideo();
            }

            @Override
            public boolean isStudentSpeakApply() {
                return liveRoomRouterListener.getSpeakApplyStatus() == RightMenuContract.STUDENT_SPEAK_APPLY_SPEAKING;
            }

            @Override
            public void attachLocalAudio() {
                liveRoomRouterListener.attachLocalAudio();
            }

            @Override
            public void setPPTOverspread() {
                liveRoomRouterListener.setPPTShowType(LPConstants.LPPPTShowWay.SHOW_COVERED);
            }

            @Override
            public void showBleDialog() {
                liveRoomRouterListener.showBleDialog();
            }
        };
    }

    @Override
    protected void initCameraContainer() {
        $.clearRefCache();
        if (!presenter.isClassStart()) {
            setCameraEnable(false);
            setDefinitionEnable(false);
            setWhichCameraEnable(false);
        } else {
            setCameraEnable(true);
            setDefinitionEnable(true);
            setWhichCameraEnable(true);
        }
        if (presenter.isReplaceCamera()) {
            setDefinitionEnable(false);
            setWhichCameraEnable(false);
        }
        if (!presenter.isTeacherOrAssistant()) {
            showStudentsHandsUp(presenter.isStudentSpeakApply());
            $.id(R.id.bjy_base_setting_camera_quality_switch)
                    .enable(presenter.isVideoAttached() && presenter.isStudentSpeakApply());
            $.id(R.id.bjy_base_setting_camera_orientation_switch)
                    .enable(presenter.isVideoAttached() && presenter.isStudentSpeakApply());
        }
        showCamera(presenter.isVideoAttached());
        showWhichCamera(presenter.getCameraOrientation());
        showCameraSwitchStatus(presenter.isVideoAttached());
        $.id(R.id.bjy_base_setting_camera_open_switch).setOnCheckedChangeListener(((buttonView, checkedPosition) -> {
            if (checkClickable(getString(R.string.bjy_base_frequent_error_switch_camera))) {
                presenter.changeCamera();
            }
        }));
        SettingSwitch definitionSwitch = $.id(R.id.bjy_base_setting_camera_quality_switch).view();
        definitionSwitch.setShowText(true);
        List<LPConstants.LPResolutionType> resolutionTypeList = getResolutionList(presenter.getMaxVideoDefinition());
        List<String> optionArray = getShowResolutionList(presenter.getMaxVideoDefinition());
        definitionSwitch.setSubOptionList(optionArray);
        definitionSwitch.setCheckedPosition(resolutionTypeList.indexOf(presenter.getVideoDefinition()));
        definitionSwitch.setOnCheckedChangeListener((MultiSwitchCompat.OnCheckedChangeListener) (buttonView, checkedPosition) -> {
            LPError lpError = presenter.setCaptureVideoDefinition(resolutionTypeList.get(checkedPosition));
            if (lpError != null) {
                showToast(lpError.getMessage());
            }
        });
        $.id(R.id.bjy_base_setting_camera_orientation_switch).setOnCheckedChangeListener((buttonView, checkedPosition) -> {
            presenter.switchCamera(checkedPosition == 0);
        });
        subscriptionOfCamera = liveRoomRouterListener.getLiveRoom().getRecorder()
                .getObservableOfCameraOn().observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {
                    setDefinitionEnable(aBoolean && !liveRoomRouterListener.getLiveRoom().getSpeakQueueVM().isReplacedUser());
                    setWhichCameraEnable(aBoolean && !liveRoomRouterListener.getLiveRoom().getSpeakQueueVM().isReplacedUser());
                    showCamera(aBoolean);
                });
    }

    @Override
    protected void initMicContainer() {
        $.clearRefCache();
        if (!presenter.isClassStart()) {
            setMicEnable(false);
            setAudioEnable(false);
        } else {
            setMicEnable(true);
            setAudioEnable(true);
        }
        showMic(presenter.isAudioAttached());
        showAudio(LiveSDKWithUI.isAudioBackOpen);
        if (!presenter.isTeacherOrAssistant()) {
            showStudentsHandsUp(presenter.isStudentSpeakApply());
        }
        $.id(R.id.bjy_base_setting_mic_open_switch).setOnCheckedChangeListener((buttonView, checkedPosition) -> {
            presenter.changeMic();
        });
        $.id(R.id.bjy_base_setting_background_audio_switch).setOnCheckedChangeListener((buttonView, checkedPosition) -> {
            LiveSDKWithUI.isAudioBackOpen = !LiveSDKWithUI.isAudioBackOpen;
            showAudio(LiveSDKWithUI.isAudioBackOpen);
        });
        subscriptionOfMic = liveRoomRouterListener.getLiveRoom().getRecorder().getObservableOfMicOn()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> showMic(aBoolean));
    }

    @Override
    protected void initRoomControlContainer() {
        $.clearRefCache();
        if (presenter.isTeacherOrAssistant()) {
            if (presenter.getRoomType() == LPConstants.LPRoomType.Multi) {

            } else if ((presenter.getRoomType() == LPConstants.LPRoomType.SmallGroup
                    || presenter.getRoomType() == LPConstants.LPRoomType.NewSmallGroup
                    || presenter.getRoomType() == LPConstants.LPRoomType.DoubleTeachers)) {
                $.id(R.id.bjy_base_setting_forbid_all_audio_text).visibility(View.VISIBLE);
                $.id(R.id.bjy_base_setting_forbid_all_audio_switch).visibility(View.VISIBLE);
                $.id(R.id.bjy_base_setting_forbid_raise_hands_text).visibility(View.GONE);
                $.id(R.id.bjy_base_setting_forbid_raise_hands_switch).visibility(View.GONE);
            } else if (presenter.getRoomType() == LPConstants.LPRoomType.Single || presenter.getRoomType() == LPConstants.LPRoomType.OneOnOne) {
                $.id(R.id.bjy_base_setting_forbid_raise_hands_text).visibility(View.GONE);
                $.id(R.id.bjy_base_setting_forbid_raise_hands_switch).visibility(View.GONE);
            }
        }
        if (!presenter.isClassStart()) {
            setForbidAllAudioEnable(false);
            setForbiddenEnable(false);
            setForbidRaiseHandEnable(false);
            setUpLinkEnable(false);
            setDownLinkEnable(false);
        } else {
            setForbidAllAudioEnable(true);
            setForbiddenEnable(true);
            setForbidRaiseHandEnable(true);
            setUpLinkEnable(true);
            setDownLinkEnable(true);
        }
        if (presenter.getWebrtcType() == 0) {
            hideMirrorMenu();
        }
        if (!presenter.isTeacherOrAssistant()) {
            hideRoomControlMenu();
        }
        if (presenter.isUseWebRTC()) {
            showUpLinkType(true);
            showDownLinkType(true);
            setUpLinkEnable(false);
            setDownLinkEnable(false);
        } else {
            showUpLinkType(presenter.getLinkType() == LPConstants.LPLinkType.TCP);
            showDownLinkType(presenter.getLinkType() == LPConstants.LPLinkType.TCP);
        }
        showForbidRaiseHand(presenter.getForbidRaiseHandStatus());

        showForbidAllAudio(presenter.getForbidAllAudioStatus());

        showForbidden(presenter.getForbidStatus(LPConstants.LPForbidChatType.TYPE_GROUP));

        onMirrorModeChange(null, presenter.getHorizontalMirrorModeSet(), presenter.getVerticalMirrorModeSet());

        showForbidAllAudio(presenter.getForbidAllAudioStatus());

        if (presenter.isGroup()) {
            setForbiddenEnable(!presenter.getForbidStatus(LPConstants.LPForbidChatType.TYPE_ALL));
        }
        $.id(R.id.bjy_base_setting_forbid_raise_hands_switch).setOnCheckedChangeListener((buttonView, checkedPosition) -> {
            presenter.switchForbidRaiseHand();
        });
        $.id(R.id.bjy_base_setting_forbid_all_switch).setOnCheckedChangeListener((buttonView, checkedPosition) -> {
            if (!presenter.switchForbidStatus()) {
                showForbidden(false);
            }
        });
        $.id(R.id.bjy_base_setting_forbid_all_audio_switch).setOnCheckedChangeListener((buttonView, checkedPosition) -> {
            presenter.switchForbidAllAudio(checkedPosition == 0);
        });

        $.id(R.id.bjy_base_setting_all_horizontal_mirror_open).clicked(v -> {
            presenter.switchAllHorizonMirrorMode(true);
        });

        $.id(R.id.bjy_base_setting_all_horizontal_mirror_close).clicked(v -> {
            presenter.switchAllHorizonMirrorMode(false);
        });

        $.id(R.id.bjy_base_setting_all_vertical_mirror_open).clicked(v -> {
            presenter.switchAllVerticalMirrorMode(true);
        });

        $.id(R.id.bjy_base_setting_all_vertical_mirror_close).clicked(v -> {
            presenter.switchAllVerticalMirrorMode(false);
        });
        $.id(R.id.bjy_base_setting_upload_load_switch).setOnCheckedChangeListener((buttonView, checkedPosition) -> {
            if (checkedPosition == 0) {
                // tcp
                if (checkClickable(getString(R.string.live_frequent_error_line))) {
                    if (presenter.getCDNCount() > 1) {
                        ArrayList<String> options = new ArrayList<>();
                        for (int i = 1; i <= presenter.getCDNCount(); i++) {
                            options.add("线路" + i);
                        }
                        if (getActivity() != null && !getActivity().isFinishing() && !getActivity().isDestroyed()) {
                            final MaterialDialog.Builder builder = new ThemeMaterialDialogBuilder(getActivity())
                                    .items(options)
                                    .itemsCallback((dialog, itemView, position, text) -> {
                                        if (presenter != null) {
                                            presenter.setUpCDNLink(position);
                                        }
                                        dialog.dismiss();
                                    });
                            builder.show();
                        }
                    } else if (presenter.getCDNCount() == 1) {
                        presenter.setUpCDNLink(0);
                    } else {
                        presenter.setUpLinkTCP();
                    }
                }
            } else {
                // udp
                if (checkClickable(getString(R.string.live_frequent_error_line))) {
                    presenter.setUpLinkUDP();
                }
            }
        });

        $.id(R.id.bjy_base_setting_download_load_switch).setOnCheckedChangeListener((buttonView, checkedPosition) -> {
            if (checkedPosition == 0) {
                // tcp
                if (checkClickable(getString(R.string.live_frequent_error_line))) {
                    if (presenter.getCDNCount() > 1) {
                        ArrayList<String> options = new ArrayList<>();
                        for (int i = 0; i <= presenter.getCDNCount(); i++) {
                            if (i == 0) {
                                options.add("自动");
                            } else {
                                options.add("线路" + i);
                            }
                        }
                        if (getActivity() == null) {
                            return;
                        }
                        new ThemeMaterialDialogBuilder(getActivity())
                                .items(options)
                                .itemsCallback((dialog, itemView, position, text) -> {
                                    presenter.setDownCDNLink(position - 1);
                                    dialog.dismiss();
                                })
                                .show();
                    } else if (presenter.getCDNCount() == 1) {
                        presenter.setDownCDNLink(0);
                    } else {
                        presenter.setDownLinkTCP();
                    }
                }
            } else {
                // udp
                if (checkClickable(getString(R.string.live_frequent_error_line))) {
                    presenter.setDownLinkUDP();
                }
            }
        });

        subscriptionOfForbidAllChat = liveRoomRouterListener.getLiveRoom().getObservableOfForbidAllChatStatus()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    //分组被全体禁言则不能操作且学生是禁言状态
                    if (result.type == LPConstants.LPForbidChatType.TYPE_ALL && liveRoomRouterListener.getLiveRoom().getCurrentUser().getGroup() != 0) {
                        setForbiddenEnable(!result.isForbid);
                    }
                    showForbidden(result.isForbid);
                });

        subscriptionOfForbidRaiseHand = liveRoomRouterListener.getLiveRoom().getObservableOfForbidRaiseHand().observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> showForbidRaiseHand(aBoolean));

        subscriptionOfForbidAllAudio = liveRoomRouterListener.getLiveRoom().getObservableOfForbidAllAudioStatus()
                .subscribe(aBoolean -> {
                    if (liveRoomRouterListener.getLiveRoom().isTeacherOrAssistant()) {
                        //老师或助教，同步静音状态
                        showForbidAllAudio(aBoolean);
                        return;
                    }
                    //学生
                    if (aBoolean && liveRoomRouterListener.getLiveRoom().getRecorder().isAudioAttached()) {
                        //静音
                        liveRoomRouterListener.getLiveRoom().getRecorder().detachAudio();
                    }
                });
        subscriptionOfDownLinkType = liveRoomRouterListener.getLiveRoom().getPlayer().getObservableOfLinkType()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(lpLinkType -> showDownLinkType(lpLinkType == LPConstants.LPLinkType.TCP));

        subscriptionOfUpLinkType = liveRoomRouterListener.getLiveRoom().getRecorder()
                .getObservableOfLinkType().observeOn(AndroidSchedulers.mainThread())
                .subscribe(lpLinkType -> {
                    showUpLinkType(lpLinkType == LPConstants.LPLinkType.TCP);
                });
    }

    @Override
    protected void hideRoomControlMenu() {
        super.hideRoomControlMenu();
    }

    @Override
    public void hideMirrorMenu() {
        $.id(R.id.bjy_base_setting_all_horizontal_mirror_text).visibility(View.GONE);
        $.id(R.id.bjy_base_setting_all_horizontal_mirror_open).visibility(View.GONE);
        $.id(R.id.bjy_base_setting_all_horizontal_mirror_close).visibility(View.GONE);
        $.id(R.id.bjy_base_setting_all_vertical_mirror_text).visibility(View.GONE);
        $.id(R.id.bjy_base_setting_all_vertical_mirror_open).visibility(View.GONE);
        $.id(R.id.bjy_base_setting_all_vertical_mirror_close).visibility(View.GONE);
    }

    @Override
    protected void initPPTContainer() {
        $.clearRefCache();
        if (!presenter.isClassStart()) {
            setRemarkSettingEnable(true);
            setPPTShowTypeEnable(true);
            setPPTViewTypeEnable(true);
            setChangePPTEnable(false);
        } else {
            setRemarkSettingEnable(true);
            setPPTShowTypeEnable(true);
            setPPTViewTypeEnable(true);
            setChangePPTEnable(true);
        }
        if (!presenter.isTeacherOrAssistant()) {
            hidePPTMenu();
        } else {
            if (shouldInitRemark) {
                mRemarksEnable = true;
                shouldInitRemark = false;
            }
        }
        if (!presenter.isTeacherOrAssistant() || presenter.getTemplateType() == LPConstants.TemplateType.VIDEO) {
            hidePPTChangeMenu();
        }
        if (liveRoomRouterListener.getPPTView().isHavePPT()) {
            if (liveRoomRouterListener.getPPTView().didRoomContainsAnimPPT()) {
                if (liveRoomRouterListener.getPPTView().didRoomContainsH5PPT()) {
                    showPPTViewType(true);
                    setPPTViewTypeEnable(false);
                } else {
                    showPPTViewType(liveRoomRouterListener.getPPTView().isAnimPPTEnable());
                }
            } else {
                showPPTViewType(false);
                setPPTViewTypeEnable(false);
            }
        } else {
            showPPTViewNoPPT();
            setPPTViewTypeEnable(false);
        }

        showChangePPTEnable(!presenter.getStudentSwitchPPTState());

        $.id(R.id.bjy_base_setting_ppt_remark_switch).check(mRemarksEnable);

        if (presenter.getPartnerConfig().PPTAnimationDisable == 1) {
            showPPTType(true);
            setPPTShowTypeEnable(false);
        } else {
            hidePPTShownType();
            liveRoomRouterListener.setPPTShowType(LPConstants.LPPPTShowWay.SHOW_FULL_SCREEN);
        }
        $.id(R.id.bjy_base_setting_ppt_remark_switch).setOnCheckedChangeListener((buttonView, checkPosition) -> {
            presenter.setRemarksEnable(!mRemarksEnable);
            mRemarksEnable = !mRemarksEnable;
            $.id(R.id.bjy_base_setting_ppt_remark_switch).check(mRemarksEnable);
        });

        $.id(R.id.bjy_base_setting_ppt_view_type_switch).setOnCheckedChangeListener((buttonView, checkedPosition) -> {
            if (checkClickable(getString(R.string.bjy_base_frequent_error_switch_ppt))) {
                if (checkedPosition == 0) {
                    if (!liveRoomRouterListener.enableAnimPPTView(true)) {
                        showSwitchPPTFail();
                    }
                } else {
                    if (!liveRoomRouterListener.enableAnimPPTView(false)) {
                        showSwitchPPTFail();
                    }
                }
            }
        });
        $.id(R.id.bjy_base_setting_student_preview_switch).setOnCheckedChangeListener((buttonView, checkedPosition) -> {
            presenter.switchChangePPTEnable(checkedPosition);
        });

        subscriptionOfChangePPT = liveRoomRouterListener.getLiveRoom().getObservableOfForbidStudentSwitchPPT()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(isEnable -> {
                    showChangePPTEnable(!isEnable);
                });
        disposableOfMirrorModeSwitch = liveRoomRouterListener.getLiveRoom().getSpeakQueueVM().getObservableOfMirrorMode()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(lpMirrorModeModel -> {
                    onMirrorModeChange(lpMirrorModeModel,
                            liveRoomRouterListener.getLiveRoom().getSpeakQueueVM().getHorizontalMirrorModeSet(),
                            liveRoomRouterListener.getLiveRoom().getSpeakQueueVM().getVerticalMirrorModeSet());
                });
    }

    @Override
    protected void initOtherContainer() {
        $.clearRefCache();
        List<LPBleDevice> bleDeviceList = presenter.getRecentBleDevices();
        if (!bleDeviceList.isEmpty()) {
            $.id(R.id.bjy_base_setting_connected_device_tv).text(bleDeviceList.get(0).name);
            if (presenter.getConnectedDevice() == null) {
                //未连接设备
                $.id(R.id.bjy_base_setting_connected_device_tv).textColor(R.color.base_live_bluetooth_gray);
                $.id(R.id.bjy_base_setting_connected_checkbox).visibility(View.GONE);
            } else {
                $.id(R.id.bjy_base_setting_connected_device_tv).setTextColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(getContext(), R.attr.base_theme_window_main_text_color));
                $.id(R.id.bjy_base_setting_connected_checkbox).visibility(View.VISIBLE);
            }
        } else {
            $.id(R.id.bjy_base_setting_connected_device_tv).visibility(View.GONE);
            $.id(R.id.bjy_base_setting_connected_checkbox).visibility(View.GONE);
        }
        $.id(R.id.bjy_base_setting_connect_tv).view().setSelected(true);
        $.id(R.id.bjy_base_setting_connect_tv).enable(true);
        $.id(R.id.bjy_base_setting_connect_tv).clicked(v -> {
            //显示蓝牙连接dialog
            presenter.showBleDialog();
        });
    }

    @Override
    public void onDestroy() {
        RxUtils.dispose(subscriptionOfForbidAllChat);
        RxUtils.dispose(subscriptionOfMic);
        RxUtils.dispose(subscriptionOfCamera);
        RxUtils.dispose(subscriptionOfForbidRaiseHand);
        RxUtils.dispose(subscriptionOfUpLinkType);
        RxUtils.dispose(subscriptionOfDownLinkType);
        RxUtils.dispose(subscriptionOfForbidAllAudio);
        RxUtils.dispose(disposableOfMirrorModeSwitch);
        RxUtils.dispose(subscriptionOfChangePPT);
        super.onDestroy();
    }
}
